package com.atguigu.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.alibaba.exception.MyException;
import com.atguigu.springcloud.alibaba.handler.MyFallBackHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class FlowLimitController{
    @GetMapping("/testA")
    // value 属性：在Sentinel中配置规则时指定的资源名称
    // blockHandler 属性：指定降级方法名称
    @SentinelResource(value = "/testA", blockHandler = "testAFallBack")
    public String testA() throws InterruptedException {

        // TimeUnit.SECONDS.sleep(2);
        // System.out.println(10 / 0);

        return "------testA";
    }

    public String testAFallBack(BlockException blockException) {
        return "test a fall back exception=" + blockException.getMessage();
    }

    @GetMapping("/testB")
    @SentinelResource(
        value = "/testB",
        blockHandlerClass = MyFallBackHandler.class,
        blockHandler = "processFallbackForTestB",
        fallbackClass = MyFallBackHandler.class,
        fallback = "resolveFallbackForTestB"
    )
    public String testB() throws MyException {

        // throw new MyException();

        return "normal test b response";
    }

    @GetMapping("/testC")
    // value 属性：在Sentinel中配置规则时指定的资源名称
    // blockHandler 属性：指定降级方法名称
    @SentinelResource(value = "testC", blockHandler = "testCFallBack")
    public String testC(@RequestParam("userName") String userName) {

        System.out.println("[原方法]userName = " + userName);

        return "------testC";
    }

    public String testCFallBack(String userName, BlockException exception) {

        System.out.println("[降级方法]userName = " + userName);
        System.out.println("[降级方法]exception = " + exception.getMessage());

        // 这里的返回值就是降级方法提供的备用结果
        return "method fall back ... testC";
    }
}